<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>承诺达标合格证管理系统</h2>
      <div class="current-time">{{ currentTime }}</div>
    </div>

    <!-- 查询条件 -->
    <el-row :gutter="20" class="query-section">
      <el-col :span="6">
        <el-form-item label="区县">
          <el-select v-model="queryParams.districtCode" placeholder="请选择区县" clearable>
            <el-option label="全部" value="" />
            <el-option label="郫都区" value="510104" />
            <el-option label="新都区" value="510114" />
            <el-option label="温江区" value="510115" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="年份">
          <el-select v-model="queryParams.year" placeholder="请选择年份">
            <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="月份">
          <el-select v-model="queryParams.month" placeholder="请选择月份" clearable>
            <el-option v-for="month in monthOptions" :key="month.value" :label="month.label" :value="month.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-col>
    </el-row>

    <!-- 统计图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <!-- 第一行 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>合格证开具数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('monthly')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="monthlyChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>主要农产品数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('product')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="productChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>每日合格证开具实时数据</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('daily')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="dailyChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>街道/镇合格证打印数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('street')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="streetChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>主体合格证开具数量排名</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('entity')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="entityChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>街道/镇用户数量统计</span>
            <el-button type="text" icon="el-icon-download" @click="downloadChart('streetUser')">下载</el-button>
          </div>
          <div class="chart-container">
            <div id="streetUserChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getStatisticsOverview } from "@/api/monitor/njt/statistics/certificate";
import * as echarts from 'echarts';

export default {
  name: "CertificateStatistics",
  data() {
    return {
      currentTime: '',
      queryParams: {
        districtCode: '',
        year: new Date().getFullYear().toString(),
        month: ''
      },
      yearOptions: [],
      monthOptions: [
        { label: '1月', value: '1' },
        { label: '2月', value: '2' },
        { label: '3月', value: '3' },
        { label: '4月', value: '4' },
        { label: '5月', value: '5' },
        { label: '6月', value: '6' },
        { label: '7月', value: '7' },
        { label: '8月', value: '8' },
        { label: '9月', value: '9' },
        { label: '10月', value: '10' },
        { label: '11月', value: '11' },
        { label: '12月', value: '12' }
      ],
      charts: {}
    };
  },
  created() {
    this.initYearOptions();
    this.updateCurrentTime();
    this.getStatisticsData();
  },
  mounted() {
    this.initCharts();
  },
  methods: {
    // 初始化年份选项
    initYearOptions() {
      const currentYear = new Date().getFullYear();
      for (let i = currentYear; i >= currentYear - 5; i--) {
        this.yearOptions.push(i.toString());
      }
    },

    // 更新当前时间
    updateCurrentTime() {
      const now = new Date();
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      this.currentTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')} ${weekdays[now.getDay()]}`;
      
      // 每秒更新时间
      setInterval(() => {
        this.updateCurrentTime();
      }, 1000);
    },

    // 获取统计数据
    getStatisticsData() {
      getStatisticsOverview(this.queryParams).then(response => {
        if (response.code === 200) {
          this.updateCharts(response.data);
        }
      });
    },

    // 查询
    handleQuery() {
      this.getStatisticsData();
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        districtCode: '',
        year: new Date().getFullYear().toString(),
        month: ''
      };
      this.getStatisticsData();
    },

    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.charts.monthly = echarts.init(document.getElementById('monthlyChart'));
        this.charts.product = echarts.init(document.getElementById('productChart'));
        this.charts.daily = echarts.init(document.getElementById('dailyChart'));
        this.charts.street = echarts.init(document.getElementById('streetChart'));
        this.charts.entity = echarts.init(document.getElementById('entityChart'));
        this.charts.streetUser = echarts.init(document.getElementById('streetUserChart'));
      });
    },

    // 更新图表
    updateCharts(data) {
      this.updateMonthlyChart(data.monthlyStatistics || []);
      this.updateProductChart(data.productStatistics || []);
      this.updateDailyChart(data.dailyStatistics || []);
      this.updateStreetChart(data.streetStatistics || []);
      this.updateEntityChart(data.entityStatistics || []);
      this.updateStreetUserChart(data.streetUserStatistics || []);
    },

    // 更新月度统计图表
    updateMonthlyChart(data) {
      const option = {
        title: {
          text: '合格证开具数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.month)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: '#409EFF'
          }
        }]
      };
      this.charts.monthly.setOption(option);
    },

    // 更新农产品统计图表
    updateProductChart(data) {
      const option = {
        title: {
          text: '主要农产品数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.productName),
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: function(params) {
              const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'];
              return colors[params.dataIndex % colors.length];
            }
          }
        }]
      };
      this.charts.product.setOption(option);
    },

    // 更新每日统计图表
    updateDailyChart(data) {
      const option = {
        title: {
          text: '每日合格证开具实时数据',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.day + '日')
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: '#67C23A'
          }
        }]
      };
      this.charts.daily.setOption(option);
    },

    // 更新街道统计图表
    updateStreetChart(data) {
      const option = {
        title: {
          text: '街道/镇合格证打印数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '合格证数量',
          type: 'pie',
          radius: '50%',
          data: data.map(item => ({
            value: item.count,
            name: item.streetName
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      this.charts.street.setOption(option);
    },

    // 更新主体统计图表
    updateEntityChart(data) {
      const option = {
        title: {
          text: '主体合格证开具数量排名',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: data.map(item => item.entityName.length > 10 ? item.entityName.substring(0, 10) + '...' : item.entityName)
        },
        series: [{
          data: data.map(item => item.count),
          type: 'bar',
          itemStyle: {
            color: '#E6A23C'
          }
        }]
      };
      this.charts.entity.setOption(option);
    },

    // 更新街道用户统计图表
    updateStreetUserChart(data) {
      const option = {
        title: {
          text: '街道/镇用户数量统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '用户数量',
          type: 'pie',
          radius: '50%',
          data: data.map(item => ({
            value: item.userCount,
            name: item.streetName
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      this.charts.streetUser.setOption(option);
    },

    // 下载图表
    downloadChart(type) {
      if (this.charts[type]) {
        const url = this.charts[type].getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff'
        });
        const link = document.createElement('a');
        link.download = `${type}_chart.png`;
        link.href = url;
        link.click();
      }
    }
  }
};
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.current-time {
  font-size: 16px;
  font-weight: 500;
}

.query-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  padding: 10px;
}

.el-form-item {
  margin-bottom: 0;
}
</style>
